import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:ui' as ui;

import 'package:leader_doctor_flutter/styles/colors.dart';

class CustomCodeFieldWidget extends StatefulWidget {
  final int maxLength; // 输入的字符最大长度
  final double fieldSize; // 输入框宽高
  final Color primaryColor; // 选中的色调
  final Color normalColor; // 常规色调
  final Size indicatorSize; // 光标的大小
  final Offset indicatorOffset; // 光标绘制的偏移量
  final TextStyle textStyle; // 文本样式
  final double spaceWidth; // 每个字符间距
  final ValueChanged<String>? onDone; // 输入完成监听
  final String initialValue; // 初始值
  final bool obscureText; // 是否为暗文显示
  final ValueChanged<String>? onChanged; // 输入内容改变监听
  final Color? backgroundColor; // 默认背景色 为白色
  final Color? fieldBackgroundColor; // 输入框背景色

  const CustomCodeFieldWidget({
    Key? key,
    this.maxLength = 6,
    this.fieldSize = 48,
    this.spaceWidth = 10,
    this.onDone,
    this.indicatorSize = const Size(1, 20),
    this.indicatorOffset = const Offset(0, 14),
    this.primaryColor =  ColorRes.colorMain,
    this.normalColor = ColorRes.colorf7f7f7,
    this.textStyle = const TextStyle(color: Color(0xFF333333), fontSize: 28),
    this.initialValue = '',
    this.obscureText = false,
    this.onChanged,
    this.backgroundColor, // 新增背景颜色参数
    this.fieldBackgroundColor, // 新增输入框背景颜色参数
  }) : super(key: key);

  @override
  _CustomCodeFieldWidgetState createState() => _CustomCodeFieldWidgetState();
}

class _CustomCodeFieldWidgetState extends State<CustomCodeFieldWidget> with WidgetsBindingObserver {
  final FocusNode _focusNode = FocusNode(); // 焦点控制
  String _inputCode = ''; // 当前输入的内容
  int _cursorValue = 0; // 用来控制光标闪烁
  Timer? _timer; // 用来控制光标闪烁的定时器

  @override
  void initState() {
    super.initState();
    _inputCode = widget.initialValue;
    _controlFocus(true);
  }

  void _controlFocus(bool focus) {
    if (focus) {
      _focusNode.requestFocus();
      _startCursorTimer();
    } else {
      _focusNode.unfocus();
      _cancelCursorTimer();
    }
  }

  void _startCursorTimer() {
    if (_timer != null) return;
    _timer = Timer.periodic(const Duration(milliseconds: 600), (timer) {
      if (mounted) {
        setState(() {
          _cursorValue += 1;
        });
      }
    });
  }

  Widget _buildField() {
    return IgnorePointer(
      child: SizedBox(
        width: 1,
        child: TextField(
          focusNode: _focusNode,
          keyboardType: TextInputType.number,
          inputFormatters: [FilteringTextInputFormatter.digitsOnly],
          maxLength: widget.maxLength,
          onChanged: (text) {
            setState(() {
              _inputCode = text;
            });
            widget.onChanged?.call(text); // 输入内容改变时调用
            if (text.length >= widget.maxLength) {
              _controlFocus(false);
              widget.onDone?.call(text);
            }
          },
        ),
      ),
    );
  }

  void _cancelCursorTimer() {
    _timer?.cancel();
    _timer = null;
  }

  @override
  void dispose() {
    _cancelCursorTimer();
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return GestureDetector(
          onTap: () => _controlFocus(true),
          child: SizedBox(
            height: widget.fieldSize,
            width: widget.fieldSize * widget.maxLength + widget.spaceWidth * (widget.maxLength - 1),
            child: Stack(
              children: [
                _buildField(),
                Container(color: widget.backgroundColor ?? ColorRes.colorFFFFFF, width: constraints.maxWidth),
                RepaintBoundary(
                  child: CustomPaint(
                    size: Size(constraints.maxWidth, widget.fieldSize),
                    painter: _CodeInputPainter(widget, _inputCode, _cursorValue),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}

class _CodeInputPainter extends CustomPainter {
  final CustomCodeFieldWidget widget;
  final String code;
  final int cursorValue;
  late Size lineSize;
  late Paint _paint;

  _CodeInputPainter(this.widget, this.code, this.cursorValue) {
    _paint = Paint()
      ..color = widget.primaryColor
      ..strokeJoin = StrokeJoin.round;
  }

  _calcLineWidth(Size size) {
    var width = size.width - ((widget.maxLength - 1) * widget.spaceWidth);
    lineSize = Size(width / widget.maxLength, 1);
  }

  @override
  void paint(Canvas canvas, Size size) {
    _calcLineWidth(size);
    _drawUnderLine(canvas, size);
    _drawIndicator(canvas, size);
    _drawText(canvas, size);
  }

  // void _drawUnderLine(Canvas canvas, Size size) {
  //   for (var i = 0; i < widget.maxLength; i++) {
  //     if (code.length == i) {
  //       _paint.color = ColorRes.colorMain;
  //       _paint.style = PaintingStyle.stroke;
  //       _paint.strokeWidth = 2;
  //     } else {
  //       _paint.color = widget.normalColor;
  //       _paint.style = PaintingStyle.stroke;
  //       _paint.strokeWidth = 1;
  //     }

  //     var rect = Rect.fromLTWH(
  //       (lineSize.width + widget.spaceWidth) * i,
  //       0,
  //       lineSize.width,
  //       size.height,
  //     );

  //     canvas.drawRRect(
  //       RRect.fromRectAndRadius(rect, Radius.circular(6)),
  //       _paint,
  //     );
  //   }
  // }

  void _drawUnderLine(Canvas canvas, Size size) {
    for (var i = 0; i < widget.maxLength; i++) {
      var rect = Rect.fromLTWH(
        (lineSize.width + widget.spaceWidth) * i,
        0,
        lineSize.width,
        size.height,
      );

      // 绘制背景颜色
      _paint.color = widget.fieldBackgroundColor ?? ColorRes.colorf7f7f7;
      _paint.style = PaintingStyle.fill;
      canvas.drawRRect(
        RRect.fromRectAndRadius(rect, Radius.circular(6)),
        _paint,
      );

      // 绘制边框
      if (code.length == i) {
        _paint.color = widget.primaryColor;
        _paint.style = PaintingStyle.stroke;
        _paint.strokeWidth = 1;
      } else {
        _paint.color = widget.normalColor;
        _paint.style = PaintingStyle.stroke;
        _paint.strokeWidth = 1;
      }
      canvas.drawRRect(
        RRect.fromRectAndRadius(rect, Radius.circular(6)),
        _paint,
      );
    }
  }

  void _drawIndicator(Canvas canvas, Size size) {
    if (cursorValue.isOdd) {
      return;
    }
    // _paint.color = ColorRes.colorMain;
    // _paint.strokeWidth = 1; // 设置线宽为1
    // var inputLength = code.length;
    // if (inputLength == widget.maxLength) return;
    // var startX = (lineSize.width + widget.spaceWidth) * inputLength + lineSize.width / 2 + widget.indicatorOffset.dx;
    // var startY = widget.indicatorOffset.dy;
    // var endY = startY + widget.indicatorSize.height;
    // canvas.drawLine(Offset(startX, startY), Offset(startX, endY), _paint);

    _paint.color = ColorRes.colorMain;
    var inputLength = code.length;
    if (inputLength == widget.maxLength) return;
    var start = (lineSize.width + widget.spaceWidth) * inputLength + lineSize.width / 2;
    var rect = Rect.fromLTWH(
      start + widget.indicatorOffset.dx,
      widget.indicatorOffset.dy,
      0.5,
      widget.indicatorSize.height,
    );
    canvas.drawRRect(
      RRect.fromRectAndRadius(rect, Radius.circular(0.25)),
      _paint,
    );
  }

  void _drawText(Canvas canvas, Size size) {
    var list = code.split("");
    for (var i = 0; i < list.length; i++) {
      var start = (lineSize.width + widget.spaceWidth) * i;

      var text = widget.obscureText ? '*' : list[i]; // 显示暗文或明文 ﹡
      var textPainter = TextPainter(
        text: TextSpan(
          text: text,
          style: widget.textStyle,
        ),
        textAlign: TextAlign.center, // 添加文本对齐方式
        textDirection: TextDirection.ltr,
      );

      textPainter.layout(minWidth: 0, maxWidth: double.infinity);

      var xOffset = start + (lineSize.width - textPainter.width) / 2;
      var yOffset = (size.height - textPainter.height) / 2;
      // textPainter.paint(canvas, Offset(xOffset, yOffset));

// 平移画布，使得字符完全居中
      canvas.save();
      canvas.translate(xOffset, yOffset + (widget.obscureText ? 4.0 : 0.0)); // 这里的偏移量可以根据需要进行微调
      textPainter.paint(canvas, Offset.zero);
      canvas.restore();
    }
  }

  Size _calcTextSize(String text) {
    final TextPainter textPainter = TextPainter(
        text: TextSpan(
          text: text,
          style: widget.textStyle,
        ),
        textDirection: TextDirection.ltr)
      ..layout(minWidth: 0, maxWidth: double.infinity);
    return textPainter.size;
  }

  ui.ParagraphStyle _convertTextStyle(TextStyle style) {
    return ui.ParagraphStyle(
      fontSize: style.fontSize,
      fontStyle: style.fontStyle,
      fontWeight: style.fontWeight,
      height: style.height,
      fontFamily: style.fontFamily,
    );
  }

  @override
  bool shouldRepaint(_CodeInputPainter oldDelegate) {
    return oldDelegate.code != code || oldDelegate.cursorValue != cursorValue;
  }
}
